#!/usr/bin/awk -f
# 系统性能监控脚本
# 分析top命令输出，生成详细的系统性能报告

BEGIN {
    print "=== 系统性能监控报告 ==="
    print "监控时间:", strftime("%Y-%m-%d %H:%M:%S")
    print "================================"
    
    # 初始化变量
    total_cpu_user = 0
    total_cpu_sys = 0
    total_cpu_idle = 0
    total_memory = 0
    used_memory = 0
    process_count = 0
    high_cpu_count = 0
    high_mem_count = 0
    
    # CPU和内存阈值
    cpu_threshold = 80
    mem_threshold = 70
}

# 处理CPU信息行
/^%Cpu/ {
    # 提取CPU使用率信息
    gsub(/[%,]/, "")
    for (i = 1; i <= NF; i++) {
        if ($i == "us") cpu_user = $(i-1)
        if ($i == "sy") cpu_sys = $(i-1)
        if ($i == "id") cpu_idle = $(i-1)
        if ($i == "wa") cpu_wait = $(i-1)
    }
    
    total_cpu_user += cpu_user
    total_cpu_sys += cpu_sys
    total_cpu_idle += cpu_idle
    cpu_samples++
}

# 处理内存信息行
/^KiB Mem/ {
    gsub(/[,]/, "")
    total_memory = $3
    used_memory = $5
    free_memory = $7
}

# 处理进程信息
/^[[:space:]]*[0-9]+/ && NF >= 12 {
    process_count++
    pid = $1
    user = $2
    cpu_percent = $9
    mem_percent = $10
    command = $12
    
    # 统计高CPU使用率进程
    if (cpu_percent > cpu_threshold) {
        high_cpu_processes[high_cpu_count++] = sprintf("PID: %s, User: %s, CPU: %s%%, Cmd: %s", 
                                                       pid, user, cpu_percent, command)
    }
    
    # 统计高内存使用率进程
    if (mem_percent > mem_threshold) {
        high_mem_processes[high_mem_count++] = sprintf("PID: %s, User: %s, MEM: %s%%, Cmd: %s", 
                                                       pid, user, mem_percent, command)
    }
    
    # 按用户统计进程数
    user_processes[user]++
    
    # 累计CPU和内存使用
    total_process_cpu += cpu_percent
    total_process_mem += mem_percent
}

END {
    # CPU使用率报告
    if (cpu_samples > 0) {
        avg_cpu_user = total_cpu_user / cpu_samples
        avg_cpu_sys = total_cpu_sys / cpu_samples
        avg_cpu_idle = total_cpu_idle / cpu_samples
        
        print "\n💻 CPU 使用率"
        printf "用户态: %.1f%%\n", avg_cpu_user
        printf "系统态: %.1f%%\n", avg_cpu_sys
        printf "空闲: %.1f%%\n", avg_cpu_idle
        printf "总使用率: %.1f%%\n", avg_cpu_user + avg_cpu_sys
        
        # CPU状态评估
        total_usage = avg_cpu_user + avg_cpu_sys
        if (total_usage > 90) {
            print "⚠️  CPU使用率过高，需要关注！"
        } else if (total_usage > 70) {
            print "⚡ CPU使用率较高"
        } else {
            print "✅ CPU使用率正常"
        }
    }
    
    # 内存使用报告
    if (total_memory > 0) {
        mem_usage_percent = (used_memory / total_memory) * 100
        
        print "\n🧠 内存使用情况"
        printf "总内存: %.1f GB\n", total_memory/1024/1024
        printf "已使用: %.1f GB (%.1f%%)\n", used_memory/1024/1024, mem_usage_percent
        printf "可用内存: %.1f GB\n", free_memory/1024/1024
        
        # 内存状态评估
        if (mem_usage_percent > 90) {
            print "⚠️  内存使用率过高，需要释放内存！"
        } else if (mem_usage_percent > 80) {
            print "⚡ 内存使用率较高"
        } else {
            print "✅ 内存使用率正常"
        }
    }
    
    # 进程统计
    print "\n📊 进程统计"
    printf "总进程数: %d\n", process_count
    if (process_count > 0) {
        printf "平均CPU使用率: %.1f%%\n", total_process_cpu/process_count
        printf "平均内存使用率: %.1f%%\n", total_process_mem/process_count
    }
    
    # 用户进程分布
    print "\n👥 用户进程分布"
    for (user in user_processes) {
        printf "%-12s: %d 个进程\n", user, user_processes[user]
    }
    
    # 高CPU使用率进程
    if (high_cpu_count > 0) {
        print "\n🔥 高CPU使用率进程 (>" cpu_threshold "%)"
        for (i = 0; i < high_cpu_count; i++) {
            print high_cpu_processes[i]
        }
    }
    
    # 高内存使用率进程
    if (high_mem_count > 0) {
        print "\n💾 高内存使用率进程 (>" mem_threshold "%)"
        for (i = 0; i < high_mem_count; i++) {
            print high_mem_processes[i]
        }
    }
    
    # 系统健康评分
    health_score = 100
    if (avg_cpu_user + avg_cpu_sys > 90) health_score -= 30
    else if (avg_cpu_user + avg_cpu_sys > 70) health_score -= 15
    
    if (mem_usage_percent > 90) health_score -= 30
    else if (mem_usage_percent > 80) health_score -= 15
    
    if (high_cpu_count > 5) health_score -= 10
    if (high_mem_count > 5) health_score -= 10
    
    print "\n🏥 系统健康评分"
    printf "健康评分: %d/100\n", health_score
    if (health_score >= 80) {
        print "✅ 系统运行良好"
    } else if (health_score >= 60) {
        print "⚡ 系统需要关注"
    } else {
        print "⚠️  系统需要紧急处理"
    }
    
    print "\n================================"
    print "监控完成 ✅"
}